from selenium import webdriver
from urllib.parse import unquote, urlparse, parse_qs
from selenium.webdriver.edge.options import Options
import requests
import os

os.makedirs('text_photos', exist_ok=True)

# 从原始URL解析实际图片地址
def extract_image_url(original_url):
    print("=========================")
    parsed_url = urlparse(original_url)
    print(parsed_url)
    print("=========================")
    query_params = parse_qs(parsed_url.query)
    print(query_params)
    objurl = query_params.get('mediaurl', [''])[0]
    return unquote(objurl)  # 解码URL编码


# 下载图片
def download_image(url, save_path):
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(1024):
                f.write(chunk)
        print(f"图片已保存至: {save_path}")
    else:
        print("下载失败，状态码:", response.status_code)


# 主程序
if __name__ == "__main__":
    # 原始页面URL
    # page_url = "https://image.baidu.com/search/detail?adpicid=0&b_applid=7939821713936825420&bdtype=15&commodity=&copyright=&cs=1189170416%2C1568964730&di=7500620934634536961&fr=click-pic&fromurl=http%253A%252F%252Fwww.hellorf.com%252Fimage%252Fshow%252F215658598&gsm=1e&hd=&height=0&hot=&ic=&ie=utf-8&imgformat=&imgratio=&imgspn=0&is=0%2C0&isImgSet=&latest=&lid=dcdc1b5401872897&lm=&objurl=https%253A%252F%252Fhellorfimg.zcool.cn%252Flarge%252F215658598.jpg&os=2412650791%2C1605615660&pd=image_content&pi=0&pn=0&rn=1&simid=1189170416%2C1568964730&tn=baiduimagedetail&width=0&word=empty%20room&z="
    # page_url2 = "https://image.baidu.com/search/detail?adpicid=0&b_applid=7939821713936825420&bdtype=0&commodity=&copyright=&cs=3931231583%2C3910989055&di=7500620934571622401&fr=click-pic&fromurl=http%253A%252F%252Fwww.hellorf.com%252Fimage%252Fshow%252F791911174%253FstatisticsType%253DFalse&gsm=1e&hd=&height=0&hot=&ic=&ie=utf-8&imgformat=&imgratio=&imgspn=0&is=0%2C0&isImgSet=&latest=&lid=dcdc1b5401872897&lm=&objurl=https%253A%252F%252Fhellorfimg.zcool.cn%252Flarge%252F791911174.jpg&os=2463445906%2C1487312532&pd=image_content&pi=0&pn=16&rn=1&simid=3931231583%2C3910989055&tn=baiduimagedetail&width=0&word=empty%20room&z="
    page_url3 = "https://cn.bing.com/images/search?view=detailV2&ccid=xubiUAZj&id=D5EBDA138A5363A4545ACCEF8D215DAFB0AA4516&thid=OIP.xubiUAZjoNomp_sBhsGPQQHaFj&mediaurl=https%3a%2f%2fwallpaperaccess.com%2ffull%2f2726468.jpg&exph=4500&expw=6000&q=empty+room&simid=607988137002992492&FORM=IRPRST&ck=DD1FB419127218B0DE00414860F12BE3&selectedIndex=0&itb=0"
    # image_url = extract_image_url(page_url)
    # image_url2 = extract_image_url(page_url2)
    image_url3 = extract_image_url(page_url3)
    # print("解析出的图片地址:", image_url)
    # print("解析出的图片地址:", image_url2)
    print("解析出的图片地址:", image_url3)

    # 初始化 Edge WebDriver
    driver = webdriver.Edge()
    # 设置 Edge 浏览器选项
    edge_options = Options()
    edge_options.add_argument('--headless')  # 无头模式
    edge_options.add_argument('--disable-gpu')
    edge_options.add_argument('--no-sandbox')
    edge_options.add_argument('--disable-dev-shm-usage')
    edge_options.add_argument('--start-maximized')  # 最大化窗口确保所有元素可见
    edge_options.add_argument('--log-level=3')  # 减少日志输出

    try:
        # 直接下载图片（绕过页面渲染）
        # save_path = f"text_photos/empty_room.jpg"
        # download_image(image_url, save_path)
        #
        # save_path = f"text_photos/empty_room2.jpg"
        # download_image(image_url2, save_path)

        save_path = f"text_photos/empty_room3.jpg"
        download_image(image_url3, save_path)
    finally:
        driver.quit()